package org.ma5d.springquartz.config;

import org.ma5d.springquartz.job.MyJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {

    /**
     * 将Job注册到Spring容器
     */
    @Bean
    public JobDetail myJob(){
        //newJob方法就是在绑定要运行的Job接口实现类,需要实现类的反射做参数
        return JobBuilder.newJob(MyJob.class)
                // 给当前JobDetail对象在调度环境中起名
                .withIdentity("myJob")
                // 将JobDetail存储在 Scheduler中，即使没有触发器绑定当前JobDetail对象,也不会被删除
                .storeDurably()
                .build();
    }

    // 下面是触发器的声明,也会保存到Spring容器中
    @Bean
    public Trigger myTrigger(){
        // 定义Cron表达式
        CronScheduleBuilder cron = CronScheduleBuilder.cronSchedule("*/2 * * * * ?"); // 每5秒执行一次
        return TriggerBuilder.newTrigger()
                // 绑定要运行的JobDetail对象
                .forJob(myJob())
                .startAt(DateBuilder.futureDate(20, DateBuilder.IntervalUnit.SECOND))       // 延迟20秒执行
                // 为触发器起名
                .withIdentity("myTrigger")
                // 绑定cron表达式
                .withSchedule(cron)
                .build();
    }
}

// 2024-09-03T09:24:45.530+08:00  INFO 2125977 --- [SpringQuartz] [           main] org.quartz.impl.StdSchedulerFactory      : Quartz scheduler version: 2.3.2
// 2024-09-03T09:24:45.534+08:00  INFO 2125977 --- [SpringQuartz] [           main] org.quartz.core.QuartzScheduler          : JobFactory set to: org.springframework.scheduling.quartz.SpringBeanJobFactory@6e5bfdfc
// 2024-09-03T09:24:46.352+08:00  INFO 2125977 --- [SpringQuartz] [           main] o.s.s.quartz.SchedulerFactoryBean        : Starting Quartz Scheduler now
// 2024-09-03T09:24:46.356+08:00  INFO 2125977 --- [SpringQuartz] [           main] org.quartz.core.QuartzScheduler          : Scheduler quartzScheduler_$_NON_CLUSTERED started.
// 2024-09-03T09:24:46.434+08:00  INFO 2125977 --- [SpringQuartz] [           main] o.m.s.SpringQuartzApplication            : Started SpringQuartzApplication in 6.716 seconds (process running for 8.771)
// 2024-09-03T09:25:04.026313904
// 2024-09-03T09:25:06.003163107
// 2024-09-03T09:25:08.003784310
// 2024-09-03T09:25:10.003107402
// 2024-09-03T09:25:12.003502499
// 2024-09-03T09:25:14.003758933
// 2024-09-03T09:25:16.002981226
// 2024-09-03T09:25:18.004164437
// 2024-09-03T09:25:20.002827882
// 2024-09-03T09:25:22.003850655